import * as moment from 'moment'

export function setObjectVolue(target = {}, source = {}, force = false) {
    for (var key in target) {
        if (source.hasOwnProperty(key)) {
            if (!force) {
                if (!isEmptyString(source[key])) {
                    target[key] = source[key]
                }
            } else {
                target[key] = source[key]
            }
        }

    }
}

export function isEmptyString(s) {
    return s === "" || s === undefined || s === null;
}


export function scrollAnimate(distance, time, dom) {
    // 20 毫秒一刷新 time
    var oldTop = dom.scrollTop
    var number = time / 20;
    var timesDitance = distance / number;
    var newT = 0;
    var interV = setInterval(() => {
        newT = newT + 20;
        if (newT <= time) {
            dom.scrollTop = dom.scrollTop + timesDitance
        } else {
            clearInterval(interV);
            dom.scrollTop = oldTop + distance;
        }
    }, 20)

}

export function isNumbers(value) {
    if (typeof value === "number") {
        return true
    } else {
        return /^[0-9\\.]+$/.test(value)
    }
}
export function isInteger(value) {
    return /^[0-9]+$/.test(value)
}


export function getLastMonthRange() {  //获取上月数据
    var nowdays = new Date();
    var year = nowdays.getFullYear();
    var month = nowdays.getMonth();
    var lastMonth = new Date(year, month, 0);
    var newYear = lastMonth.getFullYear();
    var newMonth = lastMonth.getMonth() + 1;
    newMonth = newMonth < 10 ? "0" + newMonth : newMonth;
    var newDate = lastMonth.getDate();
    return [newYear + '-' + newMonth + '-01' + ' 00:00:00', newYear + '-' + newMonth + '-' + newDate + ' 00:00:00']
}

export function getLastWeekRange() {  //获取上周数据
    var nowdays = new Date();
    var day = nowdays.getDay();
    var ss = day * 24 * 60 * 60 * 1000;
    var ss2 = (day + 6) * 24 * 60 * 60 * 1000;
    // todo 正式发版修改
    // return ["2020-11-23 00:00:00", "2020-11-29 00:00:00"]
    return [dateFormat('yyyy-mm-dd', new Date(nowdays.getTime() - ss2)) + ' 00:00:00', dateFormat('yyyy-mm-dd', new Date(nowdays.getTime() - ss)) + ' 00:00:00']
}

export function getNextWeekRange() {  //获取上周数据
    var weekOfday = (7 - moment().format('E'));//计算今天是这周第几天
    var next_monday = moment().add(weekOfday + 7, 'days');//
    var next_sunday = moment().add(weekOfday + 1, 'days');//
    return [next_sunday, next_monday]
}

export function getLastCurrentTime() {
    //todo 正式发版修改
    // return "2020-11-26 17:00:00";
    return moment().format("YYYY-MM-DD HH:mm:ss");
}


function dateFormat(fmt, date) {
    let ret;
    const opt = {
        "y+": date.getFullYear().toString(),        // 年
        "m+": (date.getMonth() + 1).toString(),     // 月
        "d+": date.getDate().toString(),            // 日
        "H+": date.getHours().toString(),           // 时
        "M+": date.getMinutes().toString(),         // 分
        "S+": date.getSeconds().toString()          // 秒
        // 有其他格式化字符需求可以继续添加，必须转化成字符串
    };
    for (let k in opt) {
        ret = new RegExp("(" + k + ")").exec(fmt);
        if (ret) {
            fmt = fmt.replace(ret[1], (ret[1].length == 1) ? (opt[k]) : (opt[k].padStart(ret[1].length, "0")))
        }
    }
    return fmt;
}

export function isNullUndefined(v) {
    return v === null || v === undefined || v === "";
}

export function getBetweenDates(sartDate, endDate, format = "YYYY-MM-DD") {
    const dates = [];
    const diffDates = endDate.diff(sartDate, 'days');
    dates.push(sartDate.format(format));
    for (let i = 1; i <= diffDates; i++) {
        dates.push(sartDate.add(1, 'd').format(format))
    }
    return dates
}

export function jsonToExcel(jsonData, excelName) {
    // let str = `姓名,电话,邮箱\n`;
    let str = ``;
    //增加\t为了不让表格显示科学计数法或者其他格式
    for (let i = 0; i < jsonData.length; i++) {
        for (let item in jsonData[i]) {
            str += `${jsonData[i][item] + '\t'},`;
        }
        str += '\n';
    }
    //encodeURIComponent解决中文乱码
    let uri = 'data:text/csv;charset=utf-8,\ufeff' + encodeURIComponent(str);
    //通过创建a标签实现
    let link = document.createElement("a");
    link.href = uri;
    //对下载的文件命名
    link.download = excelName + ".csv";
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
}


export function clearIntervalArray(list) {
    list.forEach(v => {
        if (v) {
            clearInterval(v)
        }
    })
}


export function GetCenterPoint() {
    this.points = []
}

GetCenterPoint.prototype.addP = function (p) {
    if(p){
        this.points.push(p.split(','))
    }
}
GetCenterPoint.prototype.addL = function (l) {
    if(l){
        const ls = l.split(",");
        ls.forEach((v, i) => {
            if (i % 2 > 0) {
                this.points.push([ls[i - 1], ls[i]])
            }
        })
    }

};
GetCenterPoint.prototype.getCenter = function () {
    const len = this.points.length;
    if (len == 0) {
        return;
    }
    let x = 0;
    let y = 0;
    this.points.forEach(v => {
        x = x + v[0]*1;
        y = y + v[1]*1;
    })
    return (x/len).toFixed(5)+','+ (y/len).toFixed(5);
}
export function isEmptyObject(o) {
    return Object.keys(o).length === 0
}


export function loadJs(url){
    return new Promise(resolve => {
        var script=document.createElement('script');
        script.type="text/javascript";

        if(script.readyState){
            // IE
            script.onreadystatechange=function(){
                if(script.readyState == "loaded" || script.readyState == "complete"){
                    script.onreadystatechange=null;
                    resolve()
                }
            }
        }else{
            script.onload=function(){
                resolve();
            }
        }

        script.src=url;
        document.body.appendChild(script);
    })
}

export function downloadFile (content, filename) {
    var eleLink = document.createElement('a');
    eleLink.download = filename;
    eleLink.style.display = 'none';
    // 字符内容转变成blob地址
    var blob = new Blob([content]);
    eleLink.href = URL.createObjectURL(blob);
    // 触发点击
    document.body.appendChild(eleLink);
    eleLink.click();
    // 然后移除
    document.body.removeChild(eleLink);
};
